import React, { useState, useEffect, useRef, useCallback } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { 
  Typography, 
  Button, 
  Card, 
  Table, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  InputNumber,
  message,
  Popconfirm,
  Row,
  Col,
  Breadcrumb,
  Dropdown,
  Menu,
  Upload,
  Tooltip
} from 'antd'
import { 
  PlusOutlined,
  DeleteOutlined,
  MoreOutlined,
  ImportOutlined,
  ExportOutlined,
  SaveOutlined,
  SettingOutlined,
  FileTextOutlined,
  HomeOutlined,
  PictureOutlined,
  UploadOutlined,
  EyeOutlined,
  CloseOutlined,
  HolderOutlined,
  EditOutlined
} from '@ant-design/icons'
import { DndProvider, useDrag, useDrop } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import type { ColumnsType } from 'antd/es/table'
import type { MenuProps } from 'antd'
import { StoryboardProject } from '../../../types/storyboardProject'
import { StoryboardScene, StoryboardData, ShotType } from '../../../types/document'
import { storyboardProjectService } from '../../../services/storage/storyboardProjectService'
import StoryboardTimeline from '../../components/Timeline/StoryboardTimeline'

const { Title, Paragraph } = Typography
const { TextArea } = Input

interface DragableBodyRowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  index: number
  moveRow: (dragIndex: number, hoverIndex: number) => void
}

const DragableBodyRow = ({ index, moveRow, className, style, ...restProps }: DragableBodyRowProps) => {
  const ref = useRef<HTMLTableRowElement>(null)

  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: 'row',
    collect: (monitor) => ({
      isOver: monitor.isOver(),
      dropClassName: monitor.isOver() ? 'drop-over-downward' : '',
    }),
    drop: (item: { index: number }) => {
      moveRow(item.index, index)
    },
  })

  const [, drag] = useDrag({
    type: 'row',
    item: { index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  })

  drop(drag(ref))

  return (
    <tr
      ref={ref}
      className={`${className} ${dropClassName}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  )
}

interface StoryboardRow {
  id: string
  order: number
  image?: string
  shotType: string
  duration: number
  content: string
  notes: string
  [key: string]: any
}

interface CustomColumn {
  id: string
  title: string
  dataIndex: string
  width?: number
  type: 'text' | 'number' | 'select' | 'textarea'
  options?: string[]
}

const StoryboardProjectPage: React.FC = () => {
  const { projectId } = useParams<{ projectId: string }>()
  const navigate = useNavigate()
  
  const [project, setProject] = useState<StoryboardProject | null>(null)
  const [storyboardData, setStoryboardData] = useState<StoryboardData | null>(null)
  const [rows, setRows] = useState<StoryboardRow[]>([])
  const [customColumns, setCustomColumns] = useState<CustomColumn[]>([])
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  
  const [imagePreviewVisible, setImagePreviewVisible] = useState(false)
  const [previewImage, setPreviewImage] = useState<string>('')
  const [currentImageRowId, setCurrentImageRowId] = useState<string>('')
  const [selectedRowId, setSelectedRowId] = useState<string>('')
  
  const tableRef = useRef<any>(null)

  const shotTypeOptions = [
    { value: ShotType.EXTREME_WIDE, label: '远景' },
    { value: ShotType.WIDE, label: '全景' },
    { value: ShotType.MEDIUM_WIDE, label: '中远景' },
    { value: ShotType.MEDIUM, label: '中景' },
    { value: ShotType.MEDIUM_CLOSE, label: '中近景' },
    { value: ShotType.CLOSE_UP, label: '近景' },
    { value: ShotType.EXTREME_CLOSE_UP, label: '特写' }
  ]

  const loadProject = async () => {
    console.log('[分镜项目编辑] 开始加载项目，projectId:', projectId)
    
    if (!projectId) {
      console.error('[分镜项目编辑] 项目ID无效，导航回分镜列表')
      message.error('项目ID无效')
      navigate('/storyboard')
      return
    }

    setLoading(true)
    try {
      console.log('[分镜项目编辑] 尝试获取项目数据，ID:', projectId)
      const projectData = await storyboardProjectService.getProjectById(projectId)
      console.log('[分镜项目编辑] 项目数据查询结果:', projectData)
      
      if (!projectData) {
        console.error('[分镜项目编辑] 项目不存在，导航回分镜列表')
        message.error('项目不存在')
        navigate('/storyboard')
        return
      }
      
      console.log('[分镜项目编辑] 成功加载项目:', projectData.name)
      setProject(projectData)
      
      const content = await storyboardProjectService.getProjectContent(projectId)
      console.log('[分镜项目编辑] 项目内容:', content)
      setStoryboardData(content)
      
      if (content?.scenes) {
        const tableRows = content.scenes.map((scene, index) => ({
          id: scene.id,
          order: scene.order || index + 1,
          shotType: scene.shot?.type || ShotType.MEDIUM,
          duration: scene.timing?.duration || scene.duration || 5,
          content: scene.description || scene.content || '',
          notes: scene.notes || ''
        }))
        setRows(tableRows)
        console.log('[分镜项目编辑] 生成表格行数据:', tableRows.length, '行')
      } else {
        setRows([createDefaultRow(1)])
        console.log('[分镜项目编辑] 创建默认行数据')
      }
      
    } catch (error) {
      console.error('[分镜项目编辑] 加载项目失败:', error)
      message.error('加载项目失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadProject()
  }, [projectId])

  const createDefaultRow = (order: number): StoryboardRow => ({
    id: `scene_${Date.now()}_${order}`,
    order,
    shotType: ShotType.MEDIUM,
    duration: 5,
    content: '',
    notes: ''
  })

  const handleAddRow = () => {
    const newOrder = rows.length + 1
    const newRow = createDefaultRow(newOrder)
    setRows([...rows, newRow])
  }

  const handleDeleteRow = (id: string) => {
    const newRows = rows.filter(row => row.id !== id)
    const reorderedRows = newRows.map((row, index) => ({
      ...row,
      order: index + 1
    }))
    setRows(reorderedRows)
  }

  const moveRow = useCallback((dragIndex: number, hoverIndex: number) => {
    const newRows = [...rows]
    const draggedRow = newRows[dragIndex]
    newRows.splice(dragIndex, 1)
    newRows.splice(hoverIndex, 0, draggedRow)
    
    // 重新排序
    const reorderedRows = newRows.map((row, index) => ({
      ...row,
      order: index + 1
    }))
    
    setRows(reorderedRows)
  }, [rows])

  const updateRowData = (id: string, field: string, value: any) => {
    setRows(rows.map(row => 
      row.id === id ? { ...row, [field]: value } : row
    ))
  }

  const handleSave = async () => {
    setSaving(true)
    try {
      const scenes: StoryboardScene[] = rows.map((row, index) => ({
        id: row.id,
        title: row.content || `场景 ${index + 1}`,
        description: row.content,
        order: row.order,
        shot: {
          type: row.shotType as ShotType,
          angle: 'eye_level' as any
        },
        timing: {
          duration: row.duration
        },
        sceneLocation: {
          name: '',
          type: 'interior' as any,
          lighting: 'natural_day' as any
        },
        elements: {
          characters: [],
          props: []
        },
        content: row.content,
        notes: row.notes,
        duration: row.duration
      }))

      const updatedStoryboard: StoryboardData = {
        scenes,
        totalDuration: scenes.reduce((total, scene) => total + (scene.duration || 0), 0),
        videoFormat: storyboardData?.videoFormat || {
          aspectRatio: '16:9' as any,
          resolution: '1920x1080' as any,
          frameRate: 25
        }
      }

      await storyboardProjectService.updateProjectContent(projectId!, updatedStoryboard)
      
      await storyboardProjectService.updateProject(projectId!, {
        stats: {
          sceneCount: scenes.length,
          totalDuration: updatedStoryboard.totalDuration,
          lastEditedAt: new Date().toISOString()
        }
      })

      message.success('保存成功')
    } catch (error) {
      console.error('[分镜编辑] 保存失败:', error)
      message.error('保存失败')
    } finally {
      setSaving(false)
    }
  }

  const handleImageUpload = (file: File, rowId: string) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        const base64 = e.target?.result as string
        updateRowData(rowId, 'image', base64)
        message.success('图片上传成功')
        resolve(base64)
      }
      reader.onerror = (e) => {
        message.error('图片上传失败')
        reject(e)
      }
      reader.readAsDataURL(file)
    })
  }

  const handleImagePreview = (imageUrl: string) => {
    setPreviewImage(imageUrl)
    setImagePreviewVisible(true)
  }

  const handleImageRemove = (rowId: string) => {
    updateRowData(rowId, 'image', '')
    message.success('图片已删除')
  }

  const validateImageFile = (file: File) => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
      message.error('只能上传图片文件!')
      return false
    }
    
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      message.error('图片大小不能超过5MB!')
      return false
    }
    
    return true
  }

  const handleTimelineSegmentClick = (rowId: string, order: number) => {
    setSelectedRowId(rowId)
    
    // 滚动到对应的行
    const tableContainer = document.querySelector('.ant-table-tbody')
    if (tableContainer) {
      const targetRow = tableContainer.querySelector(`tr[data-row-key="${rowId}"]`)
      if (targetRow) {
        targetRow.scrollIntoView({ 
          behavior: 'smooth', 
          block: 'center' 
        })
        
        // 高亮效果
        targetRow.classList.add('highlight-row')
        setTimeout(() => {
          targetRow.classList.remove('highlight-row')
        }, 2000)
      }
    }
  }

  const handleAddCustomColumn = () => {
    const newColumn: CustomColumn = {
      id: `custom_${Date.now()}`,
      title: '自定义',
      dataIndex: `custom_${Date.now()}`,
      width: 120,
      type: 'text',
      options: undefined
    }
    
    setCustomColumns([...customColumns, newColumn])
    message.success('自定义列添加成功')
  }

  const handleEditColumnTitle = (columnId: string, newTitle: string) => {
    setCustomColumns(prevColumns => 
      prevColumns.map(col => 
        col.id === columnId ? { ...col, title: newTitle } : col
      )
    )
  }

  const getColumns = (): ColumnsType<StoryboardRow> => {
    const baseColumns: ColumnsType<StoryboardRow> = [
      {
        title: '排序',
        key: 'order',
        width: 80,
        fixed: 'left',
        align: 'center',
        render: (_, record, index) => (
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
            padding: '4px 8px',
            borderRadius: '4px',
            transition: 'background-color 0.2s ease'
          }}
          className="drag-handle"
          >
            <HolderOutlined
              style={{
                fontSize: '16px',
                color: '#999',
                cursor: 'grab'
              }}
            />
            <span style={{
              fontSize: '14px',
              fontWeight: 500,
              color: '#333',
              minWidth: '16px',
              textAlign: 'center'
            }}>
              {index + 1}
            </span>
          </div>
        )
      },
      {
        title: '画面',
        dataIndex: 'image',
        key: 'image',
        width: 240,
        align: 'center',
        render: (value, record) => {
          const isImageData = value && value.startsWith('data:image')
          
          return (
            <div style={{ 
              display: 'flex', 
              flexDirection: 'column', 
              gap: '8px', 
              alignItems: 'center', 
              minHeight: '120px', 
              justifyContent: 'center',
              padding: '8px'
            }}>
              {isImageData ? (
                <div 
                  className="image-container"
                  style={{ 
                    position: 'relative',
                    width: '180px', 
                    height: '100px',
                    borderRadius: '6px',
                    overflow: 'hidden',
                    cursor: 'pointer',
                    border: '2px solid #e8e8e8'
                  }}
                >
                  <img 
                    src={value} 
                    alt="画面" 
                    style={{ 
                      width: '100%', 
                      height: '100%', 
                      objectFit: 'cover'
                    }}
                    onClick={() => handleImagePreview(value)}
                  />
                  
                  <div style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'rgba(0, 0, 0, 0.6)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '12px',
                    opacity: 0,
                    transition: 'opacity 0.2s ease',
                  }}
                  className="image-overlay"
                  >
                    <div style={{
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      color: 'white',
                      cursor: 'pointer',
                      fontSize: '12px'
                    }}
                    onClick={(e) => {
                      e.stopPropagation()
                      handleImagePreview(value)
                    }}
                    >
                      <EyeOutlined style={{ fontSize: '16px', marginBottom: '2px' }} />
                      <span>预览</span>
                    </div>
                    
                    <Upload
                      accept="image/*"
                      showUploadList={false}
                      beforeUpload={(file) => {
                        if (validateImageFile(file)) {
                          handleImageUpload(file, record.id)
                        }
                        return false
                      }}
                      style={{ display: 'contents' }}
                    >
                      <div style={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        color: 'white',
                        cursor: 'pointer',
                        fontSize: '12px'
                      }}
                      onClick={(e) => e.stopPropagation()}
                      >
                        <UploadOutlined style={{ fontSize: '16px', marginBottom: '2px' }} />
                        <span>更换</span>
                      </div>
                    </Upload>
                    
                    <div style={{
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      color: '#ff4d4f',
                      cursor: 'pointer',
                      fontSize: '12px'
                    }}
                    onClick={(e) => {
                      e.stopPropagation()
                      handleImageRemove(record.id)
                    }}
                    >
                      <CloseOutlined style={{ fontSize: '16px', marginBottom: '2px' }} />
                      <span>删除</span>
                    </div>
                  </div>
                </div>
              ) : (
                <Upload
                  accept="image/*"
                  showUploadList={false}
                  beforeUpload={(file) => {
                    if (validateImageFile(file)) {
                      handleImageUpload(file, record.id)
                    }
                    return false
                  }}
                >
                  <div style={{ 
                    width: '180px', 
                    height: '100px', 
                    border: '2px dashed #d9d9d9',
                    borderRadius: '6px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: '#bfbfbf',
                    cursor: 'pointer',
                    transition: 'all 0.2s ease',
                    backgroundColor: '#fafafa'
                  }}
                  className="upload-area"
                  >
                    <PlusOutlined style={{ fontSize: '24px', marginBottom: '8px' }} />
                    <div style={{ fontSize: '12px', textAlign: 'center' }}>
                      <div>点击上传图片</div>
                      <div>或拖拽图片至此区域</div>
                    </div>
                  </div>
                </Upload>
              )}
            </div>
          )
        }
      },
      {
        title: '景别',
        dataIndex: 'shotType',
        key: 'shotType',
        width: 120,
        align: 'center',
        render: (value, record) => (
          <Select
            size="small"
            value={value}
            onChange={(newValue) => updateRowData(record.id, 'shotType', newValue)}
            style={{ 
              width: '100%', 
              border: 'none',
              boxShadow: 'none'
            }}
            placeholder="输入内容"
          >
            {shotTypeOptions.map(option => (
              <Select.Option key={option.value} value={option.value}>
                {option.label}
              </Select.Option>
            ))}
          </Select>
        )
      },
      {
        title: '时长（秒）',
        dataIndex: 'duration',
        key: 'duration',
        width: 120,
        align: 'center',
        render: (value, record) => (
          <InputNumber
            size="small"
            min={0}
            max={3600}
            value={value}
            onChange={(newValue) => updateRowData(record.id, 'duration', newValue || 0)}
            style={{ 
              width: '100%', 
              textAlign: 'center',
              border: 'none',
              boxShadow: 'none'
            }}
            placeholder="5"
          />
        )
      },
      {
        title: '内容',
        dataIndex: 'content',
        key: 'content',
        width: 200,
        render: (value, record) => (
          <Input.TextArea
            rows={2}
            placeholder="输入内容"
            defaultValue={value || ''}
            onBlur={(e) => updateRowData(record.id, 'content', e.target.value)}
          />
        )
      },
      {
        title: '备注',
        dataIndex: 'notes',
        key: 'notes',
        width: 150,
        render: (value, record) => (
          <Input.TextArea
            rows={2}
            placeholder="输入内容"
            defaultValue={value || ''}
            onBlur={(e) => updateRowData(record.id, 'notes', e.target.value)}
          />
        )
      }
    ]

    // 添加自定义列
    const customColumnsRendered = customColumns.map(customColumn => ({
      title: (
        <Tooltip title="点击编辑列标题" placement="top">
          <div style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: '4px',
            cursor: 'pointer',
            padding: '2px 6px',
            borderRadius: '4px',
            transition: 'background-color 0.2s ease'
          }}
          className="editable-column-title"
          >
            <Input
              size="small"
              defaultValue={customColumn.title}
              onBlur={(e) => handleEditColumnTitle(customColumn.id, e.target.value)}
              style={{
                border: 'none',
                boxShadow: 'none',
                background: 'transparent',
                textAlign: 'center',
                fontWeight: 500,
                color: '#666',
                cursor: 'pointer',
                padding: '0 4px'
              }}
              placeholder="列标题"
            />
            <EditOutlined style={{ 
              fontSize: '12px', 
              color: '#bfbfbf',
              opacity: 0.7,
              transition: 'opacity 0.2s ease'
            }} />
          </div>
        </Tooltip>
      ),
      dataIndex: customColumn.dataIndex,
      key: customColumn.id,
      width: customColumn.width || 120,
      render: (value: any, record: StoryboardRow) => {
        const currentValue = value || ''
        
        return (
          <Input.TextArea
            rows={2}
            placeholder="输入内容"
            defaultValue={currentValue}
            onBlur={(e) => updateRowData(record.id, customColumn.dataIndex, e.target.value)}
          />
        )
      }
    }))

    const addCustomColumnButton = {
      title: (
        <Tooltip title="添加自定义列" placement="top">
          <Button
            type="text"
            size="small"
            icon={<PlusOutlined />}
            onClick={handleAddCustomColumn}
            style={{
              width: '28px',
              height: '28px',
              borderRadius: '6px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: '#1890ff',
              fontSize: '14px'
            }}
          />
        </Tooltip>
      ),
      key: 'add-column',
      width: 60,
      align: 'center' as const,
      render: () => null
    }

    const actionColumn = {
      title: '',
      key: 'operations',
      width: 50,
      fixed: 'right' as const,
      align: 'center' as const,
      render: (_, record) => (
        <Popconfirm
          title="确认删除此场景吗？"
          description="删除后无法恢复"
          onConfirm={() => handleDeleteRow(record.id)}
          okText="删除"
          cancelText="取消"
          okType="danger"
        >
          <Button 
            size="small" 
            type="text"
            danger 
            icon={<DeleteOutlined />}
            style={{
              width: '28px',
              height: '28px',
              borderRadius: '6px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          />
        </Popconfirm>
      )
    }

    return [...baseColumns, ...customColumnsRendered, addCustomColumnButton, actionColumn]
  }

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Card loading />
      </div>
    )
  }

  if (!project) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Card>
          <Title level={4}>项目不存在</Title>
          <Button type="primary" onClick={() => navigate('/storyboard')}>
            返回项目列表
          </Button>
        </Card>
      </div>
    )
  }

  return (
    <DndProvider backend={HTML5Backend}>
      <div style={{ 
        padding: '24px', 
        backgroundColor: '#f5f5f5',
        minHeight: '100vh'
      }}>
        <style>{`
          .ant-table {
            background: white;
            border-radius: 8px;
            overflow: hidden;
          }
          
          .ant-table-thead > tr > th {
            background-color: #fafafa !important;
            border: none !important;
            font-weight: 500 !important;
            color: #666 !important;
            padding: 16px 12px !important;
            text-align: center !important;
          }
          
          .ant-table-tbody > tr > td {
            padding: 12px 8px !important;
            border: none !important;
            vertical-align: middle !important;
            text-align: center !important;
          }
          
          .ant-table-tbody > tr:hover > td {
            background-color: #f8f9fa !important;
          }
          
          .ant-table-tbody > tr:not(:last-child) > td {
            border-bottom: 1px solid rgba(0, 0, 0, 0.06) !important;
          }
          
          .drop-over-downward td {
            border-bottom: 2px dashed #1890ff !important;
          }
          
          .ant-table-tbody > tr.drop-over-downward > td {
            background-color: #e6f7ff !important;
          }
          
          .image-container:hover .image-overlay {
            opacity: 1 !important;
          }
          
          .image-overlay {
            transition: opacity 0.2s ease;
          }
          
          .image-overlay > div:hover {
            transform: scale(1.1);
            transition: transform 0.1s ease;
          }
          
          .upload-area:hover {
            border-color: #1890ff !important;
            color: #1890ff !important;
            background-color: #e6f7ff !important;
          }
          
          .ant-input-small:not(.ant-input-textarea), .ant-select-small .ant-select-selector, .ant-input-number-small {
            border: none !important;
            box-shadow: none !important;
            background: transparent !important;
            border-radius: 4px !important;
          }
          
          .ant-input-small:not(.ant-input-textarea):hover, .ant-select-small:hover .ant-select-selector, .ant-input-number-small:hover {
            background-color: rgba(0, 0, 0, 0.04) !important;
          }
          
          .ant-input-small:not(.ant-input-textarea):focus, .ant-select-small.ant-select-focused .ant-select-selector, .ant-input-number-small:focus {
            border: none !important;
            box-shadow: none !important;
            background-color: rgba(24, 144, 255, 0.06) !important;
          }
          
          .ant-input-textarea {
            border: 1px solid #d9d9d9 !important;
            border-radius: 4px !important;
            padding: 4px 8px !important;
            background: white !important;
            box-shadow: none !important;
          }
          
          .ant-input-textarea:hover {
            border-color: #40a9ff !important;
          }
          
          .ant-input-textarea:focus, .ant-input-textarea.ant-input-focused {
            border-color: #1890ff !important;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
          }
          
          .ant-table-cell {
            border: none !important;
          }
          
          .ant-table-container {
            border: none !important;
          }
          
          .drag-handle:hover {
            background-color: rgba(24, 144, 255, 0.1) !important;
          }
          
          .drag-handle:active {
            background-color: rgba(24, 144, 255, 0.2) !important;
          }
          
          .ant-input-number-input {
            text-align: center !important;
          }
          
          .editable-column-title:hover {
            background-color: rgba(24, 144, 255, 0.06) !important;
          }
          
          .editable-column-title:hover .anticon-edit {
            opacity: 1 !important;
            color: #1890ff !important;
          }
          
          .highlight-row {
            background-color: #e6f7ff !important;
            animation: highlight-pulse 2s ease-in-out;
          }
          
          @keyframes highlight-pulse {
            0% { background-color: #1890ff !important; }
            50% { background-color: #e6f7ff !important; }
            100% { background-color: #f8f9fa !important; }
          }
        `}</style>
      
      <div style={{ marginBottom: '24px' }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: '16px'
        }}>
          <Breadcrumb>
            <Breadcrumb.Item>
              <HomeOutlined />
            </Breadcrumb.Item>
            <Breadcrumb.Item onClick={() => navigate('/storyboard')} style={{ cursor: 'pointer' }}>
              分镜管理
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <FileTextOutlined />
              {project?.name}
            </Breadcrumb.Item>
          </Breadcrumb>
          
          <Button 
            type="primary" 
            icon={<SaveOutlined />}
            loading={saving}
            onClick={handleSave}
            style={{
              borderRadius: '6px',
              height: '36px',
              fontWeight: 500
            }}
          >
            保存项目
          </Button>
        </div>
        
        {/* 时间轴组件 */}
        <div style={{ marginBottom: '24px' }}>
          <StoryboardTimeline 
            rows={rows}
            onSegmentClick={handleTimelineSegmentClick}
            currentSelectedId={selectedRowId}
          />
        </div>
      </div>

      <div 
        style={{ 
          borderRadius: '8px',
          overflow: 'hidden',
          backgroundColor: 'white'
        }}
      >
        <Table
          columns={getColumns()}
          dataSource={rows}
          rowKey="id"
          scroll={{ x: 1200, y: 600 }}
          pagination={false}
          size="middle"
          showHeader={true}
          bordered={false}
          components={{
            body: {
              row: (props: any) => {
                const index = rows.findIndex(row => row.id === props['data-row-key'])
                return <DragableBodyRow index={index} moveRow={moveRow} {...props} />
              }
            }
          }}
          style={{
            borderRadius: '8px',
            overflow: 'hidden'
          }}
        />
        
        <div style={{
          padding: '16px 24px',
          borderTop: '1px solid #f0f0f0',
          backgroundColor: '#fafafa',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <span style={{ color: '#666', fontSize: '14px' }}>
            总场景数: {rows.length} | 总时长: {rows.reduce((sum, row) => sum + row.duration, 0)}秒
          </span>
          <Button 
            type="dashed" 
            icon={<PlusOutlined />}
            onClick={handleAddRow}
            style={{
              borderRadius: '6px',
              height: '32px'
            }}
          >
            添加新场景
          </Button>
        </div>
      </div>

      <Modal
        title="图片预览"
        open={imagePreviewVisible}
        onCancel={() => setImagePreviewVisible(false)}
        footer={null}
        width={800}
        centered
      >
        {previewImage && (
          <div style={{ textAlign: 'center' }}>
            <img 
              src={previewImage} 
              alt="画面预览" 
              style={{ 
                maxWidth: '100%', 
                maxHeight: '500px',
                objectFit: 'contain'
              }}
            />
          </div>
        )}
      </Modal>
      </div>
    </DndProvider>
  )
}

export default StoryboardProjectPage